import 'package:cloud_medicine/components/order_row.dart';
import 'package:cloud_medicine/http/config.dart';
import 'package:cloud_medicine/http/shop_api.dart';
import 'package:cloud_medicine/main.dart';
import 'package:cloud_medicine/model/order_info.dart';
import 'package:cloud_medicine/pages/shop_detail.dart';
import 'package:flutter/material.dart';
import 'package:url_launcher/url_launcher.dart';

class OrderInfo extends StatefulWidget {
  final shopid;
  final shopname;
  final shopimage;
  final orderID;
  OrderInfo({Key key, this.orderID, this.shopid, this.shopname, this.shopimage})
      : super(key: key);

  @override
  _OrderInfoState createState() => _OrderInfoState();
}

class _OrderInfoState extends State<OrderInfo> {
  bool _loading = false;
  OrderItem _orderInfo;
  List<Map<String, dynamic>> cartList = [];
  Future<Null> _init() async {
    setState(() {
      _loading = true;
    });
    dynamic res = await getOrderInfo_api(
        '$backIP/shop/orderInfo', {'orderId': widget.orderID}); //接口路径
    _orderInfo = OrderItem.init(res['data']);
    _orderInfo.medicineItem
        .map((e) => cartList.add({
              'number': e.number,
              'picture': e.mainpicture,
              'price': e.price,
              'name': e.medicinename
            }))
        .toList();
    if (mounted) {
      setState(() {
        _loading = false;
      });
    }
    return;
  }

  @override
  void initState() {
    super.initState();
    _init();
  }

  Map<num, String> orderStatus = {
    1: '订单已下单',
    2: '订单配送中',
    3: '订单已送达',
    4: '订单已完成'
  };
  _launch() async {
    var url = 'tel:${_orderInfo.shop.shopnumber}';
    if (await canLaunch(url)) {
      await launch(url);
    } else {
      throw 'Could not launch $url';
    }
  }

  Future addChat() async {
    await addChat_api('$backIP/chat/new', {
      'ShopID': widget.shopid,
      'picture': widget.shopimage,
      'shopname': widget.shopname
    });
  }

  Widget _childLayout() {
    if (_loading) {
      return Center(
        child: Container(
          child: CircularProgressIndicator(),
        ),
      );
    } else {
      return ListView(
        children: [
          GestureDetector(
            onTap: () {
              Navigator.of(context).push(MaterialPageRoute(
                  builder: (context) => ShopDetail(
                        shopid: _orderInfo.shop.shopID,
                      )));
            },
            child: Card(
              elevation: 5,
              color: Colors.white,
              child: Container(
                margin: EdgeInsets.all(10),
                child: Column(children: [
                  Row(
                    children: [
                      Text(
                        _orderInfo.shop.shopname,
                        style: TextStyle(fontSize: 19),
                      ),
                      Icon(Icons.chevron_right),
                    ],
                  ),
                  Divider(
                    thickness: 1,
                    color: Colors.grey[300],
                  ),
                  MedicineItemList(
                    deliveryFee: _orderInfo.deliveryFee,
                    price: _orderInfo.allPrice,
                    cartList: cartList,
                  ),
                  Container(
                    margin: EdgeInsets.only(top: 10),
                    height: 30,
                    color: Colors.grey[100],
                    child: Row(
                      mainAxisAlignment: MainAxisAlignment.spaceEvenly,
                      children: [
                        GestureDetector(
                          onTap: () {
                            addChat();
                            Navigator.of(context).push(MaterialPageRoute(
                                builder: (BuildContext context) => MyHomePage(
                                      initIndex: 2,
                                    )));
                          },
                          child: Row(
                            children: [Icon(Icons.chat), Text('联系商家')],
                          ),
                        ),
                        VerticalDivider(
                          thickness: 2,
                          color: Colors.grey[50],
                        ),
                        GestureDetector(
                          onTap: () {
                            _launch();
                          },
                          child: Row(
                            children: [Icon(Icons.phone), Text('致电商家')],
                          ),
                        ),
                      ],
                    ),
                  )
                ]),
              ),
            ),
          ),
          Card(
            color: Colors.white,
            elevation: 5,
            child: Container(
              margin: EdgeInsets.all(10),
              child: Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  Container(
                    child: Text(
                      '配送信息',
                      style: TextStyle(fontSize: 17),
                    ),
                  ),
                  Divider(
                    thickness: 1,
                    color: Colors.grey[300],
                  ),
                  MyRow(
                      leftwidget: Text('配送地址'),
                      rightwidget: Text(_orderInfo.user.address)),
                  SizedBox(
                    height: 10,
                  ),
                  MyRow(
                      leftwidget: Text('收货信息'),
                      rightwidget: Text(
                          '${_orderInfo.user.name} ${_orderInfo.user.phone}'))
                ],
              ),
            ),
          ),
          Card(
            color: Colors.white,
            elevation: 5,
            child: Container(
              margin: EdgeInsets.all(10),
              child: Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  Container(
                    child: Text(
                      '订单信息',
                      style: TextStyle(fontSize: 17),
                    ),
                  ),
                  Divider(
                    thickness: 1,
                    color: Colors.grey[300],
                  ),
                  MyRow(
                      leftwidget: Text('订单号码'),
                      rightwidget: Text('${widget.orderID}')),
                  SizedBox(
                    height: 10,
                  ),
                  MyRow(
                      leftwidget: Text('下单时间'),
                      rightwidget: Text('${_orderInfo.time}')),
                ],
              ),
            ),
          ),
          Center(
            child: Container(
              margin: EdgeInsets.only(top: 10),
              child: Text(
                '到底了~',
                style: TextStyle(fontSize: 13, color: Colors.grey[600]),
              ),
            ),
          )
        ],
      );
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
        backgroundColor: Colors.grey[300],
        appBar: AppBar(
          title: Text(_orderInfo == null ? '加载中' : orderStatus[_orderInfo.id]),
        ),
        body: _childLayout());
  }
}
